package com.zmn.oms.business.impl.conf.workturn.servcategory;

import com.zmn.base.product.common.dto.categ.CategServProductDRO;
import com.zmn.base.product.common.query.categ.ForeignCategServProductQuery;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServProductListRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.mcc.common.dto.dept.DeptDRO;
import com.zmn.mcc.dubbo.interfaces.dept.DeptListRemoteService;
import com.zmn.oms.business.interfaces.conf.workturn.servcategory.PlatServCategoryBService;
import com.zmn.oms.model.entity.conf.workturn.servcategory.PlatServCategory;
import com.zmn.oms.model.entity.conf.workturn.servcategory.log.PlatServCategoryLog;
import com.zmn.oms.services.interfaces.conf.workturn.servcategory.PlatServCategoryService;
import com.zmn.oms.services.interfaces.conf.workturn.servcategory.log.PlatServcategoryLogService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PlatServCategoryBServiceImpl implements PlatServCategoryBService {

    //    @Autowired
//    private ServAssCategoryService servAssCategoryService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    CategServProductListRemoteService categServProductListRemoteService;
    @Autowired
    private PlatServCategoryService platServCategoryService;
    @Autowired
    private PlatServcategoryLogService platServcategoryLogService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private DeptListRemoteService deptListRemoteService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("Duplicates")
    public void modifyPlatServCategory(Integer plat, Integer servCategId, List<String> categoryIds, LoginStaff operator) {

        List<String> dbCategorys = platServCategoryService.listByPlatAndServCategId(plat, servCategId).stream()
                .map(item -> item.getServCategId() + "-" + item.getCategOneId() + "-" + item.getCategId()).collect(Collectors.toList());

        // 过滤平台新开通分类
        List<String> openCategoryIds = categoryIds.stream().filter(item -> !dbCategorys.contains(item)).collect(Collectors.toList());

        // 过滤平台关闭的分类
        List<String> colseCategoryIds = dbCategorys.stream().filter(item -> !categoryIds.contains(item)).collect(Collectors.toList());

        ForeignCategServProductQuery query = new ForeignCategServProductQuery();
        query.setShowType(1);
        ResponseDTO<List<CategServProductDRO>> listResponseDTO = categServProductListRemoteService.listByQuery(query);
        List<CategServProductDRO> categServProductList = listResponseDTO.getData();
        // 启用的后台分类
        Map<String, CategServProductDRO> categoryMap = categServProductList.stream()
                .collect(Collectors.toMap(item -> item.getServCategId() + "-" + item.getCategOneId() + "-" + item.getCategId(), item -> item, (p, u) -> p));

        List<PlatServCategory> insertBatch = new ArrayList<>(openCategoryIds.size());
        openCategoryIds.forEach(categoryId -> {
            String[] ids = categoryId.split("-");
            PlatServCategory serviceCategory =
                    new PlatServCategory(null, plat, Integer.valueOf(ids[0]), Integer.valueOf(ids[1]), Integer.valueOf(ids[2]), operator.getRealName(), null, DateUtil.getNow(), null);
            insertBatch.add(serviceCategory);
        });

        List<PlatServCategory> deleteBatch = new ArrayList<>(colseCategoryIds.size());
        colseCategoryIds.forEach(categoryId -> {
            String[] ids = categoryId.split("-");
            PlatServCategory serviceCategory =
                    new PlatServCategory(null, plat, Integer.valueOf(ids[0]), Integer.valueOf(ids[1]), Integer.valueOf(ids[2]), operator.getRealName(), null, DateUtil.getNow(), null);
            deleteBatch.add(serviceCategory);
        });

        StringBuffer stringBuffer = new StringBuffer();
        if (insertBatch != null && insertBatch.size() > 0) {
            platServCategoryService.insertBatch(insertBatch);
            String addStr = getTranslateStr(openCategoryIds, categoryMap);
            if (!addStr.isEmpty()) {
                stringBuffer.append("新增：").append(addStr).append("，");
            }
        }

        if (deleteBatch != null && deleteBatch.size() > 0) {
            platServCategoryService.deleteBatch(deleteBatch);
            String deleteStr = getTranslateStr(colseCategoryIds, categoryMap);
            if (!deleteStr.isEmpty()) {
                stringBuffer.append("删除：").append(deleteStr).append("，");
            }
        }

        if (stringBuffer.toString().length() > 0) {
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            PlatServCategoryLog log = new PlatServCategoryLog();
            ResponseDTO<DeptDRO> data = deptListRemoteService.getDept(operator.getDeptId());
            DeptDRO dept = new DeptDRO();
            if (data.isSuccess()) {
                dept = data.getData();
            }

            Date date = DateUtil.getNow();
            log.setPlat(plat);
            log.setDeptId(operator.getDeptId());
            log.setDeptName(dept.getDeptName());
            log.setContent(stringBuffer.toString());
            log.setCreater(operator.getRealName());
            log.setCreateTime(date);
            log.setUpdater(operator.getRealName());
            log.setUpdateTime(date);
            platServcategoryLogService.insert(log);
        }
    }

    @Override
    public Boolean checkOpenCategByPlatAndCateg(Integer plat, Integer servCategId, Integer showCategTwoId) {
        int count = platServCategoryService.countOpenCategByPlatAndCateg(plat, servCategId, showCategTwoId);
        return count > 0;
    }

    private String getTranslateStr(List<String> categIds, Map<String, CategServProductDRO> categoryMap) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < categIds.size(); i++) {
            String categoryId = categIds.get(i);
            CategServProductDRO category = categoryMap.get(categoryId);
            if (category != null) {
                stringBuffer.append(category.getServCategName()).append("-");
                stringBuffer.append(category.getCategName());
                stringBuffer.append("、");
            }
        }

        if (stringBuffer.toString().length() > 0) {
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }

        return stringBuffer.toString();
    }
}
